package com.socio.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;

import android.net.Uri;

import com.google.gson.Gson;
import com.socio.model.responses.ClientResponse;

public class SocioUtils {
	
	private static final int NUM_DAY_SEC = 86400000;
	private static final Gson gson = new Gson();
	
	/**
	 * Get day string in form of DD/MM/YYYY that represents the time passed in
	 * @param time time to be converted
	 * @return DD/MM/YYYY
	 */
	public static String dayTimeToString(long time) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(time));
		
		String dateString = ""+ (calendar.get(Calendar.MONTH)+1); 
		dateString += "/"+ calendar.get(Calendar.DAY_OF_MONTH);
		dateString += "/"+ calendar.get(Calendar.YEAR);

		return dateString;
	}
	
	/**
	 * Pass in any time and get the day time that represents it
	 * @param time any time
	 * @return corresponding day time
	 */
	public static long getDayTimeContainingTime(long time) {
		return time - (time % NUM_DAY_SEC);
	}
	
	/**
	 * Get the time that represents the equivalent of tomorrow
	 * @param time today's time
	 * @return tomorrow's time
	 */
	public static long getNextDayFromTime(long time) {
		long dayTimeOfParamater = getDayTimeContainingTime(time);
		return dayTimeOfParamater + NUM_DAY_SEC;
	}
	
	/**
	 * Get the time that represents yesterday
	 * @param time today's time
	 * @return yesterdays time
	 */
	public static long getPreviousDayFromTime(long time) {
		long dayTimeOfParamater = getDayTimeContainingTime(time);
		return dayTimeOfParamater - NUM_DAY_SEC;
	}
	
	/**
	 * Get client response from Socio URL request
	 * 
	 * @param uriBuilder request URL
	 * @param responseClass Class of response
	 * @return response object from Socio backend
	 * @throws Exception if anything goes wrong
	 */
	public static ClientResponse getResponseFromURLRequest(Uri.Builder uriBuilder, Class<? extends ClientResponse> responseClass) throws Exception {
		
		ClientResponse response = gson.fromJson(getStringFromURLRequest(uriBuilder), responseClass);		
		return response;
	}
	
	/**
	 * Get string response from url request
	 * 
	 * @param uriBuilder request URL
	 * @return response String
	 * @throws Exception if anything goes wrong
	 */
	public static String getStringFromURLRequest(Uri.Builder uriBuilder) throws Exception {
		// setup connection to URL
		URL url = new URL(uriBuilder.build().toString());
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		StringBuilder responseString = new StringBuilder();
		try {
			conn.setConnectTimeout(60000);
			conn.setRequestMethod("GET");
			conn.connect();
			
			// get results from url
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = "";
			while ((line = rd.readLine()) != null)
				responseString.append(line);
			rd.close();
		} catch (Exception e) {
			throw e;
		} finally {
			conn.disconnect();
		}
		
		return responseString.toString();
	}
	
	/**
	 * Get the time that represents today
	 * @return todays time
	 */
	public static long getTodayTime() {
		return getDayTimeContainingTime(System.currentTimeMillis());
	}
	
	/**
	 * POST JSON to url
	 * 
	 * @param uriBuilder
	 * @param request
	 * @return if post was successful
	 * @throws Exception if anything goes wrong
	 */
	public static ClientResponse postStringToURL(Uri.Builder uriBuilder, String request, Class<? extends ClientResponse> responseClass) throws Exception {
		
		// setup connection to URL
		URL url = new URL(uriBuilder.build().toString());
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		ClientResponse response = null;
		try {
			conn.setConnectTimeout(60000);
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setRequestProperty( "Content-type", "application/json" );
			conn.setRequestProperty( "Content-length", Integer.toString(request.length()));
			
			// write json to output stream
			PrintWriter out = new PrintWriter(conn.getOutputStream());
			out.print(request);
			out.flush();
			out.close();
			
			// get results from url
			InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());
			response = gson.fromJson(streamReader, responseClass);
			streamReader.close();
		} catch (Exception e) {
			throw e;
		} finally {
			conn.disconnect();
		}
		
		return response;
	}
}
